"""单元测试共用fixtures和配置"""


import pytest_asyncio

from src.models.family_model import Family, FamilyMember
from src.security import get_password_hash
from tests.conftest import TestAsyncSessionLocal


@pytest_asyncio.fixture(scope="function")
async def db_session():
    """创建干净的数据库会话 - function级别,每个测试前后清理数据"""
    async with TestAsyncSessionLocal() as session:
        # 清理所有表数据
        await session.commit()
        yield session
        await session.close()


@pytest_asyncio.fixture(scope="function")
async def test_family(db_session: TestAsyncSessionLocal):
    """创建测试家庭"""
    family = Family(name="测试家庭")
    db_session.add(family)
    await db_session.commit()
    await db_session.refresh(family)
    return family


@pytest_asyncio.fixture(scope="function")
async def test_family_member(db_session: TestAsyncSessionLocal, test_family: Family):
    """创建测试家庭成员"""
    from src.models.family_model import FamilyRole

    family_member = FamilyMember(
        username="test_user",
        email="test@example.com",
        hashed_password=get_password_hash("testpassword"),
        full_name="测试用户",
        role=FamilyRole.ADMIN,
        family_id=test_family.id,
        family_name=test_family.name,
        is_active=True,
    )
    db_session.add(family_member)
    await db_session.commit()
    await db_session.refresh(family_member)
    return family_member
